<?php
/**
 * Created by PhpStorm.
 * User: chuan
 * Date: 2014/11/23 0023
 * Time: 21:16
 */

include_once('util.php');
include_once('./lib/simple_html_dom.php');

class page {
    var $pagePath = 'localhost';
    var $html;
    var $htmlUrl;
    var $count = 0;

    var $title = '';
    var $intro = '';
    var $author = '';
    var $imgHref = '';
    var $imgTitle = '';
    var $content = '';

    public function loadPage($path) {
        $this->clear();

        $this->htmlUrl = $path;
        $this->html = file_get_html($this->htmlUrl);
        if (!empty($this->html)) {
            $this->analyse();
        } else {
            print('打开网页'.$path."失败\n");
        }

        $this->count++;
    }

    public function clear() {
        if (!empty($this->html)) {
            $this->html->clear();
            $this->init();
        }
    }

    public function printToFile() {
        if (empty($this->html)) {
            print('网页 '.$this->htmlUrl.' 内容为空，停止写入！');
            return ;
        }

        $file = fopen('./file/'.$this->count.'.md', 'w') or die('Unable to open file!');
        $text = '!['.$this->imgTitle.']('.$this->imgHref.")\n";
        $text = $text."### ".$this->title."\n";
        $text = $text.'*作者:'.$this->author.'('.$this->intro.")*\n";
        $text = $text.$this->content."\n";
        fwrite($file, $text);
        fclose($file);
    }

    private function analyse() {
        if (empty($this->html)) {
            print('网页 '.$this->htmlUrl.' 内容为空，停止分析！');
            return ;
        }

        $this->imgTitle = $this->html->find('span[class=img-source]', 0)->innertext;
        $this->title    = $this->html->find('h1[class=headline-title]', 0)->innertext;
        $this->author   = $this->html->find('span[class=author]', 0)->innertext;
        $this->intro    = $this->html->find('span[class=bio]', 0)->innertext;
        $this->content  = $this->html->find('div[class=content]', 0)->innertext;
        $this->imgHref  = $this->html->find('span[class=img-source]', 0)->next_sibling()->src;
    }

    private function init() {
        $this->htmlUrl = '';
        $this->title = '';
        $this->intro = '';
        $this->author = '';
        $this->imgHref = '';
        $this->imgTitle = '';
        $this->content = '';
    }
} 